import { useNavigate } from 'react-router-dom'
import { Button, Empty, Input, Popconfirm, Tag, message } from 'antd'
// 导入资源
import { Table, Space } from 'antd'
import { EditOutlined, DeleteOutlined } from '@ant-design/icons'
import './index.scss'
import { getOwnerBlogAPI, getUserBlogSelectAPI } from '@/api/search'
import { useSelector } from 'react-redux'
import { useEffect, useState } from 'react'
import { getBlogDeleteAPI } from '@/api/blog'
import dayjs from 'dayjs'
import moment from 'moment'


const ManageBlog = () => {
  const navigate = useNavigate()
  // 准备列数据
  const columns = [
    {
      title: '标题',
      dataIndex: 'title',
      width: 220
    },
    {
      title: '作者',
      dataIndex: 'author',
      width: 220
    },
    {
      title: '状态',
      dataIndex: 'state',
      width: 220,
      render: (data) => {
        return (
          <div>
            {data === '已发布' && <Tag color="green">{data}</Tag>}
            {data === '审核中' && <Tag color="gold">{data}</Tag>}
            {data === '草稿' && <Tag color="magenta">{data}</Tag>}
          </div>
        )
      }
    },
    {
      title: '发布时间',
      dataIndex: 'createTime',
    },
    {
      title: '博客内容',
      ellipsis: true,
      dataIndex: 'text',
      width: 300
    },
    {
      title: '操作',
      render: (data) => {
        return (
          <Space size="middle">
              <Button 
                icon={<EditOutlined />} 
                onClick={() => navigate(`/publish?id=${data.id}`)} 
                >
                  编辑
                </Button> 
              <Popconfirm
                title="确认删除该条文章吗?"
                onConfirm={() => handleBlog(data)}
                okText="确认"
                cancelText="取消"
              >
                <Button
                  danger
                  icon={<DeleteOutlined />}
                >
                  删除
                </Button>
                </Popconfirm>
          </Space>
        )
      }
    }
  ]

  // 分页
  const [params, setParams] = useState({
    page: 1,
    per_page: 5
  })
  const pageChange = (page) => {
    // 拿到当前页参数 修改params
    setParams({
      ...params,
      page
    })
}
  // 获取个人ID
  const userInfo = useSelector(state => state.user.userInfo)
  // 获取个人博客
  const [blogInfo, setBlogInfo] = useState([])
  const getOwnerBlog = async () => {
    try {
      const res = await getOwnerBlogAPI(userInfo.username)
      const filteredBlogInfo = res.data
        .filter((item) => item.state !== '下架') // 过滤掉状态为下架的博客
        .map((item) => ({
          ...item,
          createTime: dayjs(item.createTime).format('YYYY-MM-DD'),
          text: item.text.replace(/<img[^>]+>|<br>/g, '') + '...'
        }))
      setBlogInfo(filteredBlogInfo.sort((a, b) => moment(b.createTime).diff(moment(a.createTime))))
    } catch (error) {
      console.error('获取个人博客出错:', error)
    }
  }

  useEffect(() => {
    getOwnerBlog()
  }, [params])

  // 删除博客
  const handleBlog = async (data) => {
    const res = await getBlogDeleteAPI(data.id)
    if (res.code ===1) {
      message.success('删除成功')
      getOwnerBlog()
    } else {
      message.error(res.msg)
    }
  }

  const [searchText, setSearchText] = useState('')
  const onSearch = async (value) => {
    const res = await getUserBlogSelectAPI(value, userInfo.username)
    setBlogInfo(res.data)
  }
    return (
        <div className='manage-blog'>
          <div className="search">
          <Input.Search
            size='large'
            placeholder="请输入搜索内容"
            allowClear
            value={searchText}
            onChange={(e) => setSearchText(e.target.value)}
            onSearch={onSearch}/>
          </div>
            { blogInfo && blogInfo.length ?
            <Table 
              rowKey="id" 
              columns={columns} 
              dataSource={blogInfo} 
              pagination={{
                current: params.page,
                pageSize: params.per_page,
                onChange: pageChange,
                total: blogInfo && Array.isArray(blogInfo) ? blogInfo.length : 0
              }}/>
              : <div>
              <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
            </div> }
        </div>
      )
}

export default ManageBlog